package cn.tedu.order.service;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.tcc.OrderTCCAction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;


@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AccountClient accountClient;

    @Autowired
    private StorageClient storageClient;

    @Autowired
    private EasyIdClient easyIdClient;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderTCCAction orderTCCAction;

    @GlobalTransactional
    @Override
    public void create(Order order) {
        // TODO:调用全局唯一id发号器,获取一个唯一不重复的id
        String s = easyIdClient.nextId("order_business");
        Long orderId=Long.valueOf(s);

        //临时随机产生一个id,完成发号器后,这里的代码要删除
//        Long orderId = Math.abs(new Random().nextLong());

        order.setId(orderId);

//        orderMapper.create(order);
        /*
        调用TCC第一阶段的方法
            orderTCCAction 是一个动态代理对象
            其中用aop添加了拦截器,会拦截调用,在拦截器中创建上下文对象
         */
        orderTCCAction.prepare(null, order.getId(),
                order.getUserId(), order.getProductId(),
                order.getCount(), order.getMoney());

        //TODO:远程调用库存,减少商品库存
        storageClient.decrease(order.getProductId(), order.getCount());
        //TODO:远程调用账户,扣减账户金额
        accountClient.decrease(order.getUserId(), order.getMoney());
    }
}
